var speedDiv = document.getElementById('speed-div')
var clearButton = document.getElementById('clear-btn')
var speedInput = document.getElementById('speed-range')
var pauseButton = document.getElementById('pause-btn')
var modeButton = document.getElementById('mode-btn')


function pause(){
    GLOBAL_CONFIG.isRunning = false
    clearInterval(GLOBAL_CONFIG.handle)
    pauseButton.innerHTML = '开始'
}

function play(){
    GLOBAL_CONFIG.isRunning = true
    GLOBAL_CONFIG.handle = setInterval(
      nextGeneration,
      GLOBAL_CONFIG.animationSpeed,
    )
    pauseButton.innerHTML = '暂停'
}

function toggleStart() {
  if (GLOBAL_CONFIG.isRunning) {
    pause()
  } else {
    play()
  }
}

function toggleMode() {
  if (GLOBAL_CONFIG.currentStatus == SINGLE_CELL) {
    GLOBAL_CONFIG.currentStatus = PATTERN
    modeButton.innerHTML = '模式'
  } else {
    GLOBAL_CONFIG.currentStatus = SINGLE_CELL
    clearGhosts()
    modeButton.innerHTML = '单细胞'
  }
}

document.addEventListener('keydown', function(event) {
  if (event.keyCode === 32) {
    toggleStart()
  }
})

modeButton.addEventListener('click', toggleMode)

document.addEventListener('mousedown', function(event) {
  GLOBAL_CONFIG.isMouseDown = true
})
document.addEventListener('mouseup', function() {
  GLOBAL_CONFIG.isMouseDown = false
})

document.addEventListener('wheel', function(event) {
  if (event.deltaY < 0) {
    speedInput.value = Math.min(1000, parseInt(speedInput.value) + 10)
  } else {
    speedInput.value = Math.max(0, parseInt(speedInput.value) - 10)
  }
  let speed = 20000 / speedInput.value
  GLOBAL_CONFIG.animationSpeed = speed
  speedDiv.innerHTML = `速度: ${Math.floor(speedInput.value) / 20} 帧/s`

  if (GLOBAL_CONFIG.isRunning) {
    clearInterval(GLOBAL_CONFIG.handle)
    GLOBAL_CONFIG.handle = setInterval(
      nextGeneration,
      GLOBAL_CONFIG.animationSpeed,
    )
  }
})

pauseButton.addEventListener('click', toggleStart)

clearButton.addEventListener('click', function() {
  updateGenerationDiv(0)
  pause()
  GLOBAL_CONFIG.cells.forEach(function(row) {
    row.forEach(function(cell) {
      cell.classList.remove('alive')
    })
  })
})

speedInput.addEventListener('change', function() {
  let speed = 1000 - speedInput.value
  GLOBAL_CONFIG.animationSpeed = speed
  if (GLOBAL_CONFIG.isRunning) {
    clearInterval(GLOBAL_CONFIG.handle)
    GLOBAL_CONFIG.handle = setInterval(
      nextGeneration,
      GLOBAL_CONFIG.animationSpeed,
    )
  }
})
